package com.hxzy.shop.marketing.web;

import com.google.protobuf.ServiceException;
import com.hxzy.shop.utils.LogPrintUtils;
import com.hxzy.shop.vo.ApiException;
import com.hxzy.shop.vo.Result;
import com.hxzy.shop.vo.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GlobalExceptionHandler
 * @Author wengjt
 * @Date 2021/4/2914:55
 * @Description
 **/
@ControllerAdvice(basePackages = "com.hxzy.shop.marketing.controller")
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理 ServiceException 异常
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public Result serviceExceptionHandler(HttpServletRequest req, ServiceException ex) {
        LogPrintUtils.errInfo(ex);
        // 包装 Result 结果
        return Result.failed(ResultCode.FAILED, ex.getMessage());
    }

    /**
     * 处理 MissingServletRequestParameterException 异常
     *
     * SpringMVC 参数不正确
     */
    @ResponseBody
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result missingServletRequestParameterExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException ex) {
        LogPrintUtils.errInfo(ex);
        // 包装 Result 结果
        return Result.failed(ResultCode.MISSING_REQUEST_PARAM_ERROR,
                ResultCode.MISSING_REQUEST_PARAM_ERROR.getMessage());
    }

    /**
     * 处理其它 Exception 异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest req, Exception e) {
        // 记录异常日志
        LogPrintUtils.errInfo(e);
        // 返回 failed Result
        return Result.failed(ResultCode.FAILED,
                e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public Result apiExceptionHandler(HttpServletRequest req, ApiException e) {
        // 记录异常日志
        LogPrintUtils.errInfo(e);
        // 返回 failed Result
        return Result.failed(e.getErrorCode(),
                e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MultipartException.class)
    public Result fileUploadException(MultipartException e){
        // 记录异常日志
        LogPrintUtils.errInfo(e);
        return Result.failed(ResultCode.FAILED, "文件大小超过限制2M");
    }
}
